import json
import random
from hashlib import md5

import requests
from easydict import EasyDict

from cjc import project_setting
from cjc.tools.logger import Logger


class DjangoWebApi:
    base_url = 'http://localhost:8000'
    api_login = f'{base_url}/api/jwt_login/'
    api_project = f'{base_url}/api/project_c/'
    api_video_clip = f'{base_url}/api/video_record_c/'
    token = ''

    def __init__(self):
        self.log = Logger(__class__.__name__)

    def _create_header(self, token=None, c_type=None):
        if token is None:
            token = self.token
        return {"Authorization": f'jwt {token}',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36',
                'content-type': c_type,
                }

    def login(self, usr, pwd):
        md = md5()
        md.update(pwd.encode("utf-8"))
        pwd = md.hexdigest()
        payload = {
            "username": usr,
            "password": pwd
        }
        try:
            response = requests.post(self.api_login, data=payload, headers=self._create_header())
            response.encoding = 'utf-8'
            result = response.json()
            result = EasyDict(result)
            if result.code == 2000:
                self.token = result.data.token
                print("成功登录到数据平台")
        except requests.exceptions.ConnectionError as ce:
            print("链接错误，webapi.43")

    @staticmethod
    def _create_file_content(field_name, file_name, file_content: bytes, ext='file/jpeg'):
        """

        Parameters
        ----------
        field_name  字段名
        file_name  文件名
        file_content  文件内容
        ext

        Returns
        -------

        """
        return [(field_name, (file_name, file_content, ext))]

    def create_or_update_video_clip(self, proj_id=None, _id=None,
                                    cover_name=None,
                                    src_name=None,
                                    cover_content: bytes = None,
                                    src_content: bytes = None,
                                    track=None):
        """
        Parameters
        ----------
        src_name
        cover_name
        proj_id
        _id
        file_name   #这个不能是空。上传后保存文件需要这个字段
        cover_content
        src_content
        track

        Returns
        -------

        """
        src_c = self._create_file_content('src', src_name, src_content)
        cov_c = self._create_file_content('cover', cover_name, cover_content)
        src_c.extend(cov_c)
        payload = {
            "name": 'video_record_' + str(random.randint(0, 100)),
            'id': _id,
            'proj_id': proj_id,
            'weather': project_setting.weather,
            'temperature': project_setting.temperature,
            'track': json.dumps(track),
        }
        print(payload)
        response = requests.post(self.api_video_clip, data=payload, headers=self._create_header(),
                                 files=src_c)
        response.encoding = 'utf-8'
        print(response.json())
        return response.json()

    def create_or_update_project(self, name=None, author=None, cover_content: bytes = None, element_map: bytes = None):

        cover_content = self._create_file_content('cover', "cover.jpg", cover_content)
        element_content = self._create_file_content('element', "element.jpg", element_map)
        payload = {
            "name": name,
            'author': author
        }
        cover_content.extend(element_content)
        response = requests.post(self.api_video_clip, data=payload, headers=self._create_header(),
                                 files=cover_content)

        response.encoding = 'utf-8'
        print(response.json())

        return response.json()


if __name__ == '__main__':
    f = '/home/cjc/Pictures/girl.jpg'
    fc = open(f, 'rb').read()
    dwt = DjangoWebApi()
    dwt.login('superadmin', 'admin123456')
    # dwt.create_or_update_project('我是老子', fc, fc)
    # dwt.create_or_update_video_clip(None, 49,"测试文件名.jpg", fc, fc, proj_id=49, status="阿斯顿发的说法")
    # # def create_or_update_video_clip(self, proj_id=None, _id=None,
    # #                                 cover_name=None,
    # #                                 src_name=None,
    # #                                 cover_content: bytes = None,
    # #                                 src_content: bytes = None,
    # #                                 track=None):